/**
 * Created by lichong on 3/7/2018.
 */

import React from 'react';
import {Badge, Button, Divider, Row, Spin, Popover} from 'antd';
import Item from './Item'

import HttpUtils from '../../utils/HttpUtils'

import {Link} from 'react-router-dom'

class MiniCart extends React.Component {

    constructor(props) {
        super(props)
    }

    state = {
        cartItemCount: 0,
        cart : {
           items : [],
        },
        fetched: false
    }

    removeItem(item){
        console.info('remove...' + item)
    }

    showMiniCart() {
        if (!this.state.fetched) {
            var self = this;
            HttpUtils.getMiniCart({} , {
                success : function (resp) {
                    self.setState({cart:resp.data , fetched: true , cartItemCount: resp.data.totalAmount});
                },error : function (resp) {
                    console.error(resp)
                }
            })
        }
    }

    componentDidMount() {

    }

    render() {
        const content = this.state.fetched
            ?
            (
            <div style={{width: '350px'}}>
                {
                    this.state.cart.items.map((item , index) => {
                        return (
                            <Item key={index} data={item} onRemoveItem={(item) => this.removeItem(item)}/>
                        )
                    })
                }
                <Divider/>
                <Row>
                    <div className="pull-left">
                        <span>共 {this.state.cart.totalAmount} 件商品　共计￥ {this.state.cart.totalPrice}</span>
                    </div>
                    <div className="pull-right">
                        <Button><Link to="/cart">去购物车</Link></Button>
                    </div>
                </Row>
            </div>
            )
            :
            (
                <div style={{width: '350px'}}>
                    <Spin/>
                </div>
            );
        return (
            <div>
                <Popover content={content} placement="bottomLeft" onMouseEnter={() => this.showMiniCart()}>
                    <Badge count={this.state.cartItemCount}>
                        <Link to="/cart">
                            <Button style={{height: '50px', width: '150px', lineHeight: '50px'}}>我的购物车</Button>
                        </Link>
                    </Badge>
                </Popover>
            </div>
        );
    }
}

export default MiniCart;